package mysql

import (
	"CampusCloudAid/constant"
	"CampusCloudAid/models"
	"CampusCloudAid/pkg/encryptPassword"
	"log"
	"time"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

func GetPhoneOrEmail(p, str string) (user *models.Users, err error) {
	result := Conn.Where(p+" = ?", str).First(&user)
	if result.Error == gorm.ErrRecordNotFound {
		return nil, ErrUserNotExist
	} else if result.Error != nil {
		// 查询过程中发生错误
		zap.L().Error("Conn.Where(\"phone = ? OR email = ?\", phone, email).First(&user) failed", zap.Error(result.Error))
		return nil, result.Error
	}
	return user, nil
}

func Login(password, pwd string) (err error) {
	//匹配密码
	if ok := encryptPassword.BcryptCheck(password, pwd); !ok {
		return ErrInvalidPassword
	}
	return
}

func UpdateLoginTime(user *models.Users) (err error) {
	user.LoginTime = time.Now().Format("2006-01-02 15:04:05")
	/*user.LoginTime = sql.NullTime{
		Time:  time.Now(),
		Valid: true,
	}*/
	err = Conn.Model(&user).Update("login_time", user.LoginTime).Error
	if err != nil {
		log.Println("最后一次登录时间处理错误")
		return
	}
	return
}

func CheckUserPhoneExist(Phone string) (user *models.Users, err error) {
	result := Conn.Where("phone = ?", Phone).First(&user)
	if result.Error == gorm.ErrRecordNotFound {
		// 记录不存在
		return nil, nil
	} else if result.Error != nil {
		// 查询过程中发生错误
		zap.L().Error("Conn.Where(\"phone = ?\", Phone).First(&user) failed", zap.Error(result.Error))
		return nil, result.Error
	}
	return user, ErrUserPhoneExist
}

func CheckUserExist(Nickname string) (user *models.Users, err error) {
	result := Conn.Where("nickname = ?", Nickname).First(&user)
	if result.Error == gorm.ErrRecordNotFound {
		// 记录不存在
		return nil, nil
	} else if result.Error != nil {
		// 查询过程中发生错误
		zap.L().Error("DB.Where(\"username=?\", username).First(&user) failed", zap.Error(result.Error))
		return nil, result.Error
	}
	return user, ErrUserExist
}

func CheckUserEmailExist(email string) (user *models.Users, err error) {
	result := Conn.Where("email = ?", email).First(&user)
	if result.Error == gorm.ErrRecordNotFound {
		// 记录不存在
		return nil, nil
	} else if result.Error != nil {
		// 查询过程中发生错误
		zap.L().Error("DB.Where(\"email=?\", email).First(&user) failed", zap.Error(result.Error))
		return nil, result.Error
	}
	return user, ErrEmailExist
}

func Register(user *models.Users) (err error) {
	// 设置默认头像链接
	user.Avatar = constant.DefaultAvatarURL
	//保存进数据库之前需要对密码进行加密处理
	user.Password = encryptPassword.BcryptHash(user.Password)
	if err = Conn.Create(&user).Error; err != nil {
		zap.L().Error("DB.Create(&user).Error", zap.Error(err))
		return
	}
	return
}

// GetUserInfoByID 获取用户信息
func GetUserInfoByID(userID int64) (*models.Users, error) {
	var user models.Users
	if err := Conn.Select("uid", "phone", "email", "nickname", "gender", "bio", "Campus", "Avatar").First(&user, userID).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

// UpdateUserInfoByID 更新用户信息
func UpdateUserInfoByID(userID int64, fields map[string]interface{}) error { // 传入修改的参数对数据库更新；

	if err := Conn.Model(&models.Users{}).Where("uid = ?", userID).Updates(fields).Error; err != nil {
		return err
	}
	return nil
}

// UpdateUserAvatar 更新用户头像
func UpdateUserAvatar(userID int64, avatar string) error {

	// 执行数据库更新操作
	if err := Conn.Model(&models.Users{}).Where("uid = ?", userID).Update("avatar", avatar).Error; err != nil {
		return err
	}

	return nil
}

// ReceivedTasksByID 查询用户接收的单子
func ReceivedTasksByID(userID int64) ([]*models.TaskWithUsername, error) {
	var tasks []*models.TaskWithUsername
	// 使用ORM查询功能，根据用户ID查询相关的任务单
	if err := Conn.Where("receiver_id = ?", userID).Order("publish_time DESC").Find(&tasks).Error; err != nil {
		return nil, err
	}

	// 循环遍历每个任务，查出发布者的用户名信息，并存储在 TaskWithUsername 结构中
	for _, task := range tasks {
		var publisherName string
		if err := Conn.Model(&models.Users{}).Select("nickname").Where("uid = ?", task.PublisherId).Row().Scan(&publisherName); err != nil {
			return nil, err
		}
		task.PublishName = publisherName
	}

	return tasks, nil
}

// CreatedTasksByID   查询用户创建的单子
func CreatedTasksByID(userID int64) ([]*models.TaskWithUsername, error) {
	var tasks []*models.TaskWithUsername
	// 使用ORM查询功能，根据用户ID查询相关的任务单
	if err := Conn.Where("publisher_id = ?", userID).Order("publish_time DESC").Find(&tasks).Error; err != nil {
		return nil, err
	}

	// 循环遍历每个任务，查出发布者的用户名信息，并存储在 TaskWithUsername 结构中
	for _, task := range tasks {
		var publisherName string
		if err := Conn.Model(&models.Users{}).Select("nickname").Where("uid = ?", task.PublisherId).Row().Scan(&publisherName); err != nil {
			return nil, err
		}
		task.PublishName = publisherName
	}

	return tasks, nil
}

// GetUserNicknameByPublishID 通过 publish_id 查询用户的 nickname
//func GetUserNicknameByPublishID(publishID uint) (string, error) {
//	var user models.Users
//	// 使用 ORM 查询用户表中的 nickname，根据 publish_id 查询对应的用户
//	if err := Conn.Model(&models.Users{}).Select("nickname").Where("uid = ?", publishID).First(&user).Error; err != nil {
//		return "", err
//	}
//	return user.Nickname, nil
//}
